"""
:synopsis: Creates Blank NG911 Standard Feature Class
:authors: Riley Baird (OK), Emma Baker (OK)
"""


# lib import
from ...lib.session import config
from ...lib.datachanges import StandardFeatureClassCreation
import sys
import os
import arcpy
import random
import pandas as pd
from arcgis.features import GeoAccessor, GeoSeriesAccessor
try:
    from typing import ClassVar, Optional, Union, Protocol, TypeVar, Generic, TypeVar, overload, get_args, Literal
except:
    pass


random_start_phrase = random.choice(['Make it so!', 'Hello World!', 'As the prophecy foretold...', 'Greetings earthlings.', 'All are bases are belong to us.', 'The Jig is up!'])

required_dataset_name: str = config.gdb_info.required_dataset_name # "NG911"
optional_dataset_name: str = config.gdb_info.optional_dataset_name # "OptionalLayers"
tool_switch: str = "CREATE_BLANKFC"

error_list = ["--SHOULDN'T BE USED--", "--SHOULDN'T BE USED--", "--SHOULDN'T BE USED--"]


class CreateBlankFCTool:
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "3 - Create Blank Standard Feature Classes"
        self.description = "Creates Blank NG911 Standard Feature Class."
        self.canRunInBackground = False
        self.category = "1 - Prep"

    def getParameterInfo(self):
        """Define parameter definitions"""

        params = []

        geodatabase = arcpy.Parameter(
            displayName="NG911 Standard Geodatabase",
            name="geodatabase",
            datatype="DEWorkspace",
            parameterType="Required",
            direction="Input")
        params += [geodatabase]

        std_fc_name_value_list = [[fc_name, False] for fc_name in config.required_feature_class_names]
        fc_table = arcpy.Parameter(
            displayName="Standard Feature Classes",
            name="fc_table",
            datatype="GPValueTable",
            parameterType="Optional",
            direction="Input")
        fc_table.columns = [['GPString', 'Standard Name', 'ReadOnly'], ['GPBoolean', 'Create Blank Feature Class?']]
        fc_table.values = std_fc_name_value_list
        params += [fc_table]

        # OUTPUT
        out_fc = arcpy.Parameter(
            displayName="Output Feature Classes",
            name="output_feature_classes",
            datatype="DEFeatureClass",
            parameterType="Derived",
            direction="Output",
            multiValue=True
        )
        params += [out_fc]

        return params

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""
        return

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return

    def execute(self, parameters, messages):
        """The source code of the tool."""
        gdb_path = parameters[0].valueAsText
        fc_table = parameters[1].values
        output_fc_paths: list[str] = []
        fc_dict = {}
        for idx, value_list in enumerate(fc_table):  # Loop through once
            std_fc_name = value_list[0]
            blank_fc = value_list[1]
            if not blank_fc or blank_fc in ["False", "false", "None", "none", "", " ", "#"]:
                blank_fc = False
            if not blank_fc:
                continue
            fc_dict[std_fc_name] = [None, blank_fc]
        arcpy.AddMessage(f"{random_start_phrase}")
        if fc_dict:
            arcpy.AddMessage(f"Creating and Adding Standard Feature Classes")
            for std_fc_name in fc_dict.keys():
                current_user_fc_path = fc_dict[std_fc_name][0]
                current_user_blank_fc = fc_dict[std_fc_name][1]
                config_fc = config.get_feature_class_by_name(std_fc_name)
                std_fc_geom = config_fc.geometry_type
                # not blank fc and not current_user_fc_path
                if not current_user_blank_fc and not current_user_fc_path:
                    arcpy.AddWarning(f"Um, how? There is no FC and Blank FC is False, so how did it get added to the dictionary?")
                    continue
                implement_user_std_fc = StandardFeatureClassCreation(gdb_path, std_fc_name)
                bad_fc_results = implement_user_std_fc.create_blank_fc(std_fc_geom)
                if bad_fc_results:
                    arcpy.AddWarning(f"Did not successfully create the blank standard feature class.\n\n{bad_fc_results}")
                    continue
                else:
                    output_fc_paths.append(implement_user_std_fc.std_fc_path)

                arcpy.AddMessage(f"\t`{std_fc_name}` successfully created.")

        parameters[-1].values = output_fc_paths

        return


if __name__ == "__main__":
    raise Exception("This module is a dependency of an ArcGIS Python Toolbox and should not be executed directly.")